//index.js
//获取应用实例
const app = getApp()
const bleSender = require('../../utils/bleSender.js')
import {ab2hex,inArray,byteToString} from "../../utils/util"
import {genearteData,getServiceUUIDs} from "../../utils/BLEUtil"

Page({
  timer:null,
  system:'android',
  data: {
    _discoveryStarted:false,
    advertiseStart: false,
    discoveryReady:false,
    advertiseReady:false,
    payload:'',
    devices: [
    ],
    scanResult:'',
    servers: [],
    serverId: '',
   
  },

  gotoConfig(){
    wx.navigateTo({
      url: '/pages/config/config',
    })
  },

  onLoad(){
    this.initSystemInfo()
    this.initPayload();
    this.initAdvertiseAdapter()
    this.initDiscoveryAdapter()
  },
  onUnload() {
    this.stopAdvertising()
    this.data.servers.forEach(server => {
      server.close()
    })
  },

  initSystemInfo(){
    const {system} = wx.getSystemInfoSync();
    console.log('system',system)
    this.system = system
  },
  initPayload(){
    wx.getStorage({
      key: 'payload',
      success:(res)=>{
        if(res.data){
          this.setData({payload:res.data})
        }
      }
    })
  },
  onPayloadChange(e){
    const payload = e.detail .value
    // console.log('payload',payload)
    this.setData({payload})
  },
  initDiscoveryAdapter(){
    wx.openBluetoothAdapter({
      // mode: 'peripheral',
      success: (res) => {
        console.log('initDiscoveryAdapter success', res)
        this.initBluetoothDevicesDiscovery();
      },
      fail: (res) => {
        console.log("initDiscoveryAdapter ble unavailable!",res)
        // wx.showModal({
        //   content:'初始化失败',
        //   cancelColor: 'cancelColor',
        // })
      }
    })
  },


  initAdvertiseAdapter(){
    wx.openBluetoothAdapter({
      mode: 'peripheral',
      success: (res) => {
        console.log('initAdvertiseAdapter success', res)
        this.createBLEPeripheralServer()
      },
      fail: (res) => {
        console.log("initAdvertiseAdapter ble unavailable!",res)
        // wx.showModal({
        //   content:'初始化失败',
        //   cancelColor: 'cancelColor',
        // })
      }
    })
  },
  
  startSendAndDiscovery(){
    let payload = this.data.payload
    payload = payload.replace(/\s+/g,'')
    if(!payload || payload.length === 0){
      wx.showModal({
        content:'请填写payload',
        cancelColor: 'cancelColor',
      })
      return
    }
    wx.setStorage({
      data: payload,
      key: 'payload',
    })
    if(!this.data.discoveryReady ){
      wx.showModal({
        content:'初始化未成功',
        cancelColor: 'cancelColor',
      })
      console.log('接收初始化失败')
      this.initDiscoveryAdapter()
      return
    }

    if(!this.data.advertiseReady){
      wx.showModal({
        content:'初始化未成功',
        cancelColor: 'cancelColor',
      })
      console.log('发送初始化失败')
      this.initAdvertiseAdapter()
    }
    this.setData({scanResult:''})
    setTimeout(() => {
      this.startBluetoothDevicesDiscovery() 
    }, 100);
    const actPayload = genearteData(payload);
    this.startAdvertising(actPayload)
  },
initBluetoothDevicesDiscovery(){
  if (this.data._discoveryStarted) {
    return
  }
  if(!this.data._discoveryStarted){
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      powerLevel: "high",
      // services: ['11:22:33:44:55:66'],
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success! ', res)
        this.setData({discoveryReady:true})
      },
      fail:(res)=>{
        console.log('startBluetoothDevicesDiscovery failed! ', res)
      }
    })
  }
},
  
  startBluetoothDevicesDiscovery() {
    if(this.data._discoveryStarted)
      return
      this.onBluetoothDeviceFound()
      this.setData({"_discoveryStarted":true})

  },
  stopBluetoothDevicesDiscovery() {
    if(!this.data._discoveryStarted)
      return
    this.setData({"_discoveryStarted":false})
    wx.offBluetoothDeviceFound()
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name ||  !device.localName  || device.name != 'TEMPAABBCD' ) {
          return
        }
         console.log('device',device)
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        let hexData = ab2hex(device.advertisData)
        hexData = hexData.substring(4)
        this.setData({"_discoveryStarted":false})
         device.data = hexData
        this.stopAdvertising();
        this.setData({scanResult:device.data})
      })
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this.setData({"_discoveryStarted":false})
  },
  createBLEPeripheralServer() {
    wx.createBLEPeripheralServer().then(res => {
      console.log('createBLEPeripheralServer', res)
      this.data.servers.push(res.server)
      this.server = res.server
      this.setData({ advertiseReady:true,serverId: this.server.serverId })
    })
  },
  closeServer() {
    this.server.close()
  },
 
  startAdvertising(actPayload) {
    const isIos = this.system.indexOf('iOS') >= 0
    const isIos13 = isIos && this.system.indexOf('13.') >= 0

    const uuids = getServiceUUIDs(actPayload,isIos13)
    this.server.startAdvertising({
      advertiseRequest: {
        connectable: true,
        deviceName: isIos?'11':'',
        serviceUuids:isIos?uuids:[],
        manufacturerData:isIos?[]:[ {
          manufacturerId: '0x00C7',
          manufacturerSpecificData: actPayload,
        }]
      },
      powerLevel: 'high'
    }).then(res => {
      console.log('startAdvertising', res)
      this.setData({ advertiseStart: true })
      this.stopTimer();
      this.timer = setTimeout(()=>{
        this.stopAdvertising()
      },30000)
    }, res => {
      this.setData({ advertiseStart: false })
      console.log("fail: ", res)
    })
  },
  stopTimer(){
    if(this.timer){
      clearTimeout(this.timer)
      this.time = null
    }
  },


  stopAdvertising() {
    this.stopTimer();
    this.stopBluetoothDevicesDiscovery()
   
    if (this.server) {
      this.server.stopAdvertising()
      this.setData({ advertiseStart: false })
    }
  
  },
})
